from typing import List, Optional
from fastapi import APIRouter, Depends, Path
from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr, Field, ConfigDict

from app.models import get_db
from app.services.user_service import UserService
from app.utils.response import Response
from app.utils.pagination import BasePage

router = APIRouter(prefix="/users", tags=["用户管理"])

# 请求模型
class UserCreate(BaseModel):
    """用户创建请求模型"""
    username: str = Field(..., description="用户名", example="johndoe")
    email: EmailStr = Field(..., description="邮箱", example="john@example.com")
    password: str = Field(..., description="密码", example="secret123")

class UserUpdate(BaseModel):
    """用户更新请求模型"""
    username: Optional[str] = Field(None, description="用户名", example="johndoe")
    email: Optional[EmailStr] = Field(None, description="邮箱", example="john@example.com")
    password: Optional[str] = Field(None, description="密码", example="newsecret123")
    is_active: Optional[bool] = Field(None, description="是否激活", example=True)

# 响应模型
class RoleInfo(BaseModel):
    """角色信息模型（用于嵌入用户返回模型）"""
    id: int
    name: str
    code: str
    description: Optional[str] = None
    
    model_config = ConfigDict(from_attributes=True)

class UserOut(BaseModel):
    """用户返回模型"""
    id: int
    username: str
    email: str
    is_active: bool
    roles: Optional[List[RoleInfo]] = []
    
    model_config = ConfigDict(from_attributes=True)

# API接口
@router.post("", response_model=dict)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
    """创建用户"""
    new_user = UserService.create_user(
        db, 
        username=user.username, 
        email=user.email, 
        password=user.password
    )
    return Response.success(UserOut.from_orm(new_user))

@router.get("/{user_id}", response_model=dict)
def get_user(user_id: int = Path(..., description="用户ID"), db: Session = Depends(get_db)):
    """获取单个用户"""
    user = UserService.get_user_by_id(db, user_id)
    return Response.success(UserOut.from_orm(user))

@router.get("", response_model=dict)
def get_user_list(
    page_params: BasePage = Depends(),
    db: Session = Depends(get_db)
):
    """获取用户列表"""
    result = UserService.get_user_list(db, page_params.page, page_params.page_size)
    result['items'] = [UserOut.from_orm(user) for user in result['items']]
    return Response.page_success(data=result['items'], total=result['total'])

@router.put("/{user_id}", response_model=dict)
def update_user(
    user_update: UserUpdate,
    user_id: int = Path(..., description="用户ID"),
    db: Session = Depends(get_db)
):
    """更新用户"""
    user = UserService.update_user(db, user_id, **user_update.dict(exclude_unset=True))
    return Response.success(UserOut.from_orm(user))

@router.delete("/{user_id}", response_model=dict)
def delete_user(user_id: int = Path(..., description="用户ID"), db: Session = Depends(get_db)):
    """删除用户"""
    UserService.delete_user(db, user_id)
    return Response.success(data={"message": f"用户 {user_id} 已删除"})
